/**
 * $Id: UserAction.java,v 1.2 2006/03/17 11:32:18 phil Exp $
 *
 * Copyright Commerce, Inc. All Rights Reserved.
 */
package com.vip.example.action;

import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import com.vip.example.bl.GroupManager;
import com.vip.example.entity.Group;
import com.vip.example.entity.User;
import com.vip.framework.action.BaseAction;
import com.vip.framework.generic.GenericBl;
import com.vip.framework.util.Constants;

/**
 * 用户控制类,使用泛型实现,也可扩展BaseDispatchAction
 * 
 * @author sai
 *
 */
public class UserAction extends BaseAction {
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionForward forward = null;
        String path = mapping.getPath();
        //String parameter = mapping.getParameter();
        //String method = request.getParameter(parameter);
        log.debug("path:" + path);
        if ("/listUser".equals(path)) {//用户列表
            forward = listUser(mapping, form, request, response);
        } else if ("/viewUser".equals(path)) {//用户查看
            forward = viewUser(mapping, form, request, response);
        } else if ("/editUser".equals(path)) {//用户修改
            forward = editUser(mapping, form, request, response);
        } else if ("/saveUser".equals(path)) {//用户保存
            forward = saveUser(mapping, form, request, response);
        } else if ("/removeUser".equals(path)) {//用户删除
            forward = removeUser(mapping, form, request, response);
        } else {
            forward = listUser(mapping, form, request, response);
        }

        return forward;
    }

    /**
     * 用户列表
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward listUser(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        //表单数据初始化
        DynaActionForm daf = (DynaActionForm) form;
        String page = daf.getString("page");//页数
        String rowsPerPage = daf.getString("rowsPerPage");//每页记录数
        if ("".equals(page) || null == page) {
            page = "1";
            daf.set("page", page);
            //无page值，说明是缺省进入或从修改页进入，清空表单值
            daf.set("account", "");
            daf.set("name", "");
        }
        if ("".equals(rowsPerPage) || null == rowsPerPage) {
            rowsPerPage = Constants.ROWS_PER_PAGE;
            daf.set("rowsPerPage", rowsPerPage);
        }
        
        //查询条件封装
        HashMap con = new HashMap();
        con.put("account", daf.getString("account"));
        con.put("name", daf.getString("name"));
        //提交查询
        GenericBl<User> mgr = (GenericBl<User>) getBean("userManager");
        List<User> users = mgr.search(con, Integer.parseInt(page), Integer
                .parseInt(rowsPerPage));
        log.info(users);
        log.info(users.size());
        request.setAttribute("users", users);
        return mapping.findForward("success");
    }

    /**
     * 用户查看
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward viewUser(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
    	GenericBl<User> mgr = (GenericBl<User>) getBean("userManager");
        String id = request.getParameter("id");
        User user = null;
        if (null != id && !"".equals(id)) {
            user = mgr.get(Long.valueOf(id));
        }
        if (null == user) {
            //用户不存在，转到出错页
            setErrorMessage(request, "error.user.inexistence");
            return mapping.findForward("error");
        }
        request.setAttribute("user", user);
        return mapping.findForward("success");
    }

    /**
     * 用户修改
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward editUser(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        GroupManager gMgr = (GroupManager) getBean("groupManager");
        List groups = gMgr.getAllGroup();
        request.setAttribute("groups", groups);
        
        String id = request.getParameter("id");
        if (null != id && !"".equals(id)) {
            //有id值，表明是修改用户，取用户实体
        	GenericBl<User> mgr = (GenericBl<User>) getBean("userManager");
            User user = mgr.get(Long.valueOf(id));
            if (null != user) {
                //根据用户属性设置表单值
                DynaActionForm daf = (DynaActionForm) form;
                PropertyUtils.copyProperties(daf, user);
                daf.set("groupId",user.getGroup().getId().toString());
            } else {
                //用户不存在，转到出错页
                setErrorMessage(request, "error.user.inexistence");
                return mapping.findForward("error");
            }
        }

        return mapping.findForward("success");
    }

    /**
     * 用户保存
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward saveUser(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        DynaActionForm daf = (DynaActionForm) form;
        User user = new User();
        //建议不要使用这个Utils,因为单元测试不好创建form.手动赋值.目前找不到好的方法.
        //我试了一下StrutsTestCase,好像对web.xml 2.4支持不好就没用,谁有更好的办法测试
        //Action也可以提交.
//      PropertyUtils.copyProperties(user, daf);
        Long id=(null!=daf.get("id"))?(Long)daf.get("id"):null;
        user.setId(id);
        user.setAccount(daf.getString("account"));
        user.setName(daf.getString("name"));
        user.setPassword(daf.getString("password"));

        GroupManager gMgr = (GroupManager) getBean("groupManager");
        Group group = gMgr.getGroup(Long.valueOf(daf.getString("groupId")));
        user.setGroup(group);
        GenericBl<User> mgr = (GenericBl<User>) getBean("userManager");
        mgr.save(user);
        return mapping.findForward("success");
    }

    /**
     * 用户删除
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward removeUser(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        String id = request.getParameter("id");
        if (null != id && !"".equals(id)) {
        	GenericBl<User> mgr = (GenericBl<User>) getBean("userManager");
            mgr.delete(Long.valueOf(id));
        }
        return mapping.findForward("success");
    }
}